﻿using System;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace Rison.DBHelper
{
    public sealed class DatabaseConfigInfo
    {
        private static DatabaseConfigInfo _instance = null;

        private string _defaultConnectionString = string.Empty;

        private string _tempConnectionString = string.Empty;

        private DatabaseConfigInfo()
        {
        }

        static DatabaseConfigInfo()
        {
            _instance = new DatabaseConfigInfo();
        }

        public static DatabaseConfigInfo Instance
        {
            get { return _instance; }
        }

        public string DbConnectionString
        {
            get
            {
                if(string.IsNullOrEmpty (_defaultConnectionString))
                    if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["connectionString"]))
                    {
                        _defaultConnectionString = ConfigurationSettings.AppSettings["connectionString"];
                    }

                return _defaultConnectionString;
            }
        }


        public string TempConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_tempConnectionString))
                    if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["OtherConnectionString"]))
                    {
                        _tempConnectionString = ConfigurationSettings.AppSettings["OtherConnectionString"];
                    }

                return _tempConnectionString;
            }
        }

        public string GetSqErrorlMessage(SqlException ex, string sql)
        {
            StringBuilder builder = new StringBuilder();

            switch (ex.Number)
            {
                case -17:
                    builder.Append("连接数据库失败，连接配置错误或访问权限不足被拒绝。"); break;
                case -574:
                    builder.Append("当前数据存在外键约束不能直接删除，请先删除关联的数据。"); break;
                case -2627:
                    builder.Append("当前数据的主键已存在，请检查输入的数据，修改后重新保存。"); break;
                case -2601:
                    builder.Append("当前数据的唯一约束已存在，请检查输入的数据，修改后重新保存。"); break;
                case -8152:
                    builder.Append("当前存在输入超长的值，请检查修改后重新保存。"); break;
                default:
                    builder.AppendFormat("执行数据库操作错误，错误号：{0}\n", ex.Number.ToString());
                    builder.AppendFormat("{0}\n", ex.Message);
                    builder.AppendFormat("语句：{0}", sql);
                    break;
            }

            DbExecuteLog.Instance.CreateLog(builder.ToString());

            return builder.ToString();
        }
    }
}
